<template>
  <div v-loading="loading">
    <div id="print-wrap">
      <table class="table table-bordered vertical-align-middle text-center">
        <colgroup>
          <col width="14%" />
          <col width="20%" />
          <col width="14%" />
          <col width="19%" />
          <col width="14%" />
          <col width="19%" />
        </colgroup>
        <tbody>
          <tr>
            <td>主体姓名</td>
            <td>{{ relatedData.customer_name || '' }}</td>
            <td>放款金额</td>
            <td :class="tdClass">
              <span v-if="isViewMode">{{ relatedData.reply_funds }} 万元</span>
              <el-input
                v-else
                placeholder="放款金额"
                clearable
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.reply_funds"
              >
                <span slot="append">万元</span>
              </el-input>
            </td>
            <td>贷款期限</td>
            <td :class="tdClass">
              <span v-if="isViewMode">{{ relatedData.months }} 月</span>
              <el-input
                v-else
                placeholder="贷款期限"
                clearable
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.months"
              >
                <span slot="append">月</span>
              </el-input>
            </td>
          </tr>
          <tr>
            <td>担保费率</td>
            <td>{{ relatedData.gua_rate || '-' }} %</td>
            <td>保费缴纳方式</td>
            <td>一次性缴纳</td>
            <td>应缴担保费</td>
            <td>{{ relatedData.gua_fee }} 元</td>
          </tr>
          <tr>
            <td>贷款利率</td>
            <td>
              <span class="px-2">{{ relatedData.load_rate || '-' }}</span>
              %
            </td>
            <td>放款时间</td>
            <td :class="tdClass">
              <span class="px-2" v-if="isViewMode">
                {{ $utils.dateFormat(relatedData.load_date, 'yyyy年MM月dd日') }}
              </span>
              <el-date-picker
                v-else
                v-model="editData.load_date"
                :clearable="false"
                type="date"
                placeholder="放款开始时间"
                class="w-100"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
            <td>到期时间</td>
            <td :class="tdClass">
              <span class="px-2" v-if="isViewMode">
                {{ $utils.dateFormat(relatedData.load_end_date, 'yyyy年MM月dd日') }}
              </span>
              <el-date-picker
                v-else
                v-model="editData.load_end_date"
                :clearable="false"
                type="date"
                placeholder="放款结束时间"
                class="w-100"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
          </tr>

          <tr>
            <!-- <td>担保机构</td>
            <td>{{relatedData.service_name}}</td> -->
            <td>还款付息方式</td>
            <td colspan="5">
              <div v-if="isViewMode" class="row">
                <div class="col d-flex align-items-center">
                  <span>{{ enumRepayType[relatedData.repay_method] || '-' }}</span>
                </div>
                <div class="col">
                  <el-button @click="showViewRepayList">查看还款计划</el-button>
                </div>
              </div>
              <div v-else>
                <div class="d-flex align-items-center text-left">
                  <el-radio-group v-model="repayType" @change="onRepayTypeChange">
                    <el-radio v-for="(value, key) in enumRepayType" :label="key" :key="key">
                      {{ value }}
                    </el-radio>
                  </el-radio-group>
                  <el-button @click="showRepayList" class="ml-4">生成还款计划</el-button>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>放款凭证</td>
            <td colspan="5" class="text-left">
              <div v-if="isViewMode">
                <div class="empty-wrap" v-if="!attachList.length">暂无附件（推荐函）</div>
                <attach-list v-else :attath-data="viewList" :show-label="false"></attach-list>
              </div>
              <upload-oss
                v-else
                multiple
                ref="attachUpload"
                :dir="dir"
                :file-list="attachList"
                :on-complete="handleAttachComplete"
              ></upload-oss>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="text-center" v-if="!isViewMode">
      <el-button class="btn-long" type="primary" :loading="saveLoading" @click="handlePass">
        登记
      </el-button>
      <el-button class="btn-long" :disabled="saveLoading" @click="handleDismiss">取消</el-button>
    </div>

    <repay-plan-dialog
      ref="repay"
      @getData="getRepayList"
      :visible.sync="repayVisible"
      :query-id="queryId"
      :year="repayYear"
      :view-mode="isViewMode"
      :repay-method="+repayType"
    ></repay-plan-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumRepayType } from '@/credit/plugins/enum'
import { deleteOss } from '@/common/api/oss'
import { attachAdapter } from '@/bank/components/attach/index'

import RepayPlanDialog from '@/credit/components/repay/RepayPlanDialog'
import AttachList from '@/bank/components/attach/List'

export default {
  components: {
    RepayPlanDialog,
    AttachList,
  },
  props: {
    viewMode: { type: Boolean, default: true },
    queryId: String,
  },
  data() {
    return {
      loading: false,
      saveLoading: false,
      params: {},
      tableName: 'customer_related_quick',
      isReviewApiError: true,
      relatedData: {},

      // 还款计划
      repayType: '',
      enumRepayType,
      repayList: [],
      repayVisible: false,
      editData: {
        reply_funds: '',
        months: '',
        load_date: '',
        load_end_date: '',
        repay_method: 0,
      },

      // 放款凭证
      attachTag: '放款凭证',
      attachList: [],
      attachAready: [],
      viewList: [],
      dir: 'bank/fast/register',
    }
  },
  computed: {
    ...mapGetters(['org', 'user']),
    isViewMode() {
      return this.viewMode
    },
    tdClass() {
      return this.isViewMode ? '' : 'input-td'
    },
    repayMonthType() {
      return +this.editData.repay_method === 1
    },
    repayYear() {
      return Math.ceil(+this.editData.months / 12)
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.params['customer_related_id.eq'] = this.queryId
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getData() {
      if (!this.queryId) return
      this.isReviewApiError = true
      this.loading = true
      Promise.all([
        this.$api.getData({
          table: this.tableName,
          params: this.params,
        }),
        this.$api
          .getData({
            table: 'datum_customer_attachment',
            params: {
              'customer_related_id.eq': this.queryId,
              'attachment_type.eq': this.attachTag,
            },
          })
          .then(res => res.data || []),
      ])
        .then(([res, attach]) => {
          this.isReviewApiError = false
          this.relatedData = res?.data?.[0] ?? {}
          this.attachAready = attach
          this.init()
        })
        .finally(() => {
          this.loading = false
        })
    },

    init() {
      const { relatedData } = this
      Object.keys(this.editData).forEach(key => {
        this.editData[key] = relatedData[key] || ''
      })
      this.editData.reply_funds =
        +relatedData.reply_funds || +relatedData.approved_funds || +relatedData.apply_funds || ''
      this.repayType = relatedData.repay_method

      // 附件
      this.attachList = this.attachAready.map(attachAdapter)
      this.viewList = [
        {
          tag: this.attachTag,
          attachs: this.attachList,
        },
      ]
    },

    getRepayList(data = []) {
      this.repayList = data
    },

    handleDismiss() {
      this.$refs.repay.handleInit()
      this.$emit('dismiss', this.repayVisible)
    },

    handlePass() {
      if (this.isReviewApiError) {
        return this.$message.error('获取登记信息失败，请刷新重试！')
      }
      this.onSave()
    },

    onSave() {
      this.$utils.msgbox({
        message: `确定登记?`,
        type: 'info',
        beforeClose: () => this.$refs.attachUpload.submit(),
      })
    },

    registerData() {
      const data = {
        ...this.editData,
        loan_register_status: 1,
      }
      return this.$api
        .updateData(this.$serviceName, this.tableName, this.queryId, data)
        .then(res => {
          this.$message.success('登记成功！')
          this.$emit('success', res)
          this.$refs.repay.addRepayList()
        })
        .catch(err => {
          this.$message.error(`登记失败，请重试！`)
          throw new Error(err)
        })
    },

    // 还款计划
    showViewRepayList() {
      this.repayVisible = true
    },

    showRepayList() {
      if (this.repayList.length > 1) {
        this.repayVisible = true
        return
      }
      if (!+this.editData.repay_method) {
        return this.$message.warning('请先选择还款设置')
      }
      const period = +this.editData.months || 0
      if (!period) {
        return this.$message.warning('没有用款期限')
      }
      this.repayVisible = true
    },

    onRepayClose() {
      this.repayVisible = false
    },

    onRepayTypeChange(val) {
      if (this.repayList.length < 2) {
        this.editData.repay_method = val
        return
      }
      this.repayType = this.editData.repay_method
      this.$confirm('已经有还款计划，更换还款设置后需要重新生成，确定修改？', '提示', {
        confirmButtonText: '确定修改',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$refs.repay.initRepayList()
          this.repayType = val
          this.editData.repay_method = val
        })
        .catch(() => {})
    },

    handleAttachComplete(files) {
      const { attachAready } = this
      const addFiles = files.filter(file => !attachAready.find(it => it.attachment === file.url))
      const deleteFiles = attachAready.filter(it => !files.find(file => file.url === it.attachment))

      const promise = []
      if (files.length) {
        promise.push(
          this.$api.addBatch(
            'credit',
            'datum_customer_attachment',
            addFiles.map(it => ({
              attachment: it.url,
              attachment_type: this.attachTag,
              customer_related_id: this.queryId,
              file_type: 2,
              remark: it.name,
            }))
          )
        )
      }
      if (deleteFiles.length) {
        promise.push(
          this.$api.deleteData({
            table: 'datum_customer_attachment',
            id: deleteFiles.map(it => it.id).join(','),
          }),
          deleteOss(deleteFiles.map(it => it.attachment))
        )
      }
      this.saveLoading = true
      return Promise.all(promise)
        .then(() => {
          return this.registerData()
        })
        .then(() => {
          this.attachList = files
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.input-td /deep/ .el-input-group__append {
  background-color: #ffe;
  border: none;
}
.input-td {
  background-color: #ffffee;
}
</style>
